package gphoto.services.impl;

import gphoto.bo.PhotoBean;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.sanselan.ImageReadException;
import org.apache.sanselan.ImageWriteException;
import org.apache.sanselan.Sanselan;
import org.apache.sanselan.formats.jpeg.JpegImageMetadata;
import org.apache.sanselan.formats.jpeg.exifRewrite.ExifRewriter;
import org.apache.sanselan.formats.tiff.TiffImageMetadata;
import org.apache.sanselan.formats.tiff.constants.ExifTagConstants;
import org.apache.sanselan.formats.tiff.write.TiffOutputDirectory;
import org.apache.sanselan.formats.tiff.write.TiffOutputField;
import org.apache.sanselan.formats.tiff.write.TiffOutputSet;

import algutil.filter.ImageFilter;

import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.MetadataException;

public class PhotoServicesImpl {

	private final static Logger log = Logger.getLogger(PhotoServicesImpl.class);

	private static PhotoServicesImpl photoServices = null;

	private PhotoServicesImpl() {
	}

	public static PhotoServicesImpl getInstance() {

		if (photoServices == null) {
			photoServices = new PhotoServicesImpl();
		}
		return photoServices;
	}

	public List<PhotoBean> recupererPhotos(File rep)
			throws JpegProcessingException, MetadataException,
			ImageReadException, IOException {

		File[] photos = rep.listFiles(new ImageFilter());
		List<PhotoBean> pb = new ArrayList<PhotoBean>();
		for (int i = 0; i < photos.length; i++) {
			pb.add(new PhotoBean(photos[i]));
		}
		return pb;
	}

	public int affecterIdToPhoto(PhotoBean p) throws ImageReadException,
			ImageWriteException, IOException {

		File tempFile = new File(p.getParent() + File.separator + "zzz_temp_"
				+ p.getName());
		p.renameTo(tempFile);

		if (!tempFile.exists()) {
			log.error("ERROR : impossible de renommer le fichier '"
					+ p.getPath() + "' en '" + tempFile.getPath() + "'");
		}

		JpegImageMetadata jpegMetadata = (JpegImageMetadata) Sanselan
				.getMetadata(tempFile);
		if (jpegMetadata != null) {
			TiffImageMetadata exif = jpegMetadata.getExif();
			if (exif != null) {
				TiffOutputSet outputSet = exif.getOutputSet();

				TiffOutputField colorspace = TiffOutputField.create(
						ExifTagConstants.EXIF_TAG_USER_COMMENT,
						outputSet.byteOrder, "mon commentaire...");
				TiffOutputDirectory exifDirectory = outputSet
						.getOrCreateExifDirectory();
				exifDirectory.add(colorspace);

				OutputStream outputStream = new BufferedOutputStream(
						new FileOutputStream(p.getFile()));
				new ExifRewriter().updateExifMetadataLossless(tempFile,
						outputStream, outputSet);
				outputStream.close();
			}
		}
		return -1;
	}
}
